package com.lbc.common.advice;

import com.fasterxml.jackson.databind.exc.InvalidFormatException;
import com.lbc.common.exception.CustomException;
import com.lbc.common.resp.ResponseResult;
import org.apache.shiro.authz.AuthorizationException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author xyl
 * @date 2021-03-16 20:24
 */
@RestControllerAdvice
public class ExceptionControllerAdvice {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseResult methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        // 从异常对象中拿到ObjectError对象
        ObjectError objectError = e.getBindingResult().getAllErrors().get(0);
        // 然后提取错误提示信息进行返回
        return ResponseResult.error(objectError.getDefaultMessage());
    }

    @ExceptionHandler(AuthorizationException.class)
    public ResponseResult authorizationException(AuthorizationException e) {
        return ResponseResult.error("无权限!");
    }

    @ExceptionHandler(InvalidFormatException.class)
    public ResponseResult authorizationException(InvalidFormatException e) {
        return ResponseResult.error("日期格式有误!");
    }
    @ExceptionHandler(CustomException.class)
    public ResponseResult customException(CustomException e) {
        return ResponseResult.error(e.getMessage());
    }
}
